package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.atguigu.jxc.dao.ReturnListDao;
import com.atguigu.jxc.dao.ReturnListGoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.ReturnList;
import com.atguigu.jxc.entity.ReturnListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.GoodsService;
import com.atguigu.jxc.service.ReturnListGoodsService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2023-01-29 22:52 星期日
 * description:
 */
@Service
public class ReturnListGoodsServiceImpl implements ReturnListGoodsService {

    @Autowired
    ReturnListDao returnListDao;

    @Autowired
    UserDao userDao;

    @Autowired
    ReturnListGoodsDao returnListGoodsDao;

    @Autowired
    GoodsService goodsService;

    /**
     * 退货单保存
     * @param returnList
     * @param returnListGoodsStr
     * @return
     */
    @Override
    public ServiceVO save(ReturnList returnList, String returnListGoodsStr) {

        //将json字符串（returnListGoodsStr）转换成实体类
        List<ReturnListGoods> returnListGoodsList = JSONArray.parseArray(returnListGoodsStr, ReturnListGoods.class);

        //获取当前用户id
        User currentUser = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        returnList.setUserId(currentUser.getUserId());

        //保存returnList
        returnListDao.save(returnList);

        //获取returnList的主键id
        Integer returnListId = returnList.getReturnListId();

        //为每个returnListGoods设置returnListId
        for (ReturnListGoods returnListGoods : returnListGoodsList) {
            returnListGoods.setReturnListId(returnListId);

            //退货时扣除库存
            Integer goodsNum = returnListGoods.getGoodsNum();
            String goodsCode = returnListGoods.getGoodsCode();
            boolean ifChange = goodsService.changeInventoryQuantity(goodsCode, -goodsNum);
            if (ifChange == false){
                return new ServiceVO(ErrorCode.CHANGE_INVENTORY_QUANTITY_ERROR,ErrorCode.CHANGE_INVENTORY_QUANTITY_ERROR_MSG);
            }
        }

        //批量保存returnListGoods
        returnListGoodsDao.bachSave(returnListGoodsList);

        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    /**
     * 退货单商品信息
     * @param returnListId
     * @return
     */
    @Override
    public Map<String, Object> goodsList(Integer returnListId) {
        Map<String,Object> map = new HashMap<>();

        List<ReturnListGoods> returnListGoodsList = returnListGoodsDao.goodsList(returnListId);
        map.put("rows",returnListGoodsList);
        return map;
    }
}
